package com.service;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service

public class MessageService {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    public void sendMessage()
    {
        amqpTemplate.convertAndSend("exchange", null,"1");
        amqpTemplate.convertAndSend("exchange", null, "2");
    }


    @RabbitListener(queues = {"messageQuen"})
    public void recvMessage(Message msg, final Channel channel)
    {
        System.out.println("收到消息:"+new String(msg.getBody()));
        Long  msgId  = msg.getMessageProperties().getDeliveryTag();

        try {
            Object value = redisTemplate.boundValueOps(msgId).get();
            if (value!=null)
            {
                channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
                return;
            }
            Thread.sleep(1000*3); //模拟业务
            channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
            redisTemplate.boundValueOps(msgId).set("1",1, TimeUnit.DAYS);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
